﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Web.Api.Server.Models;
using Web.Api.Server.ViewModels;

namespace Web.Api.Server.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ShopsController : ControllerBase
    {
        private readonly ApplicationDbContext _dbContext;

        public ShopsController(ApplicationDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        [HttpPost]
        [ProducesResponseType(typeof(ResponseViewModel<int>), 200)]
        public async Task<IActionResult> Post(ShopsPostViewModel viewModel)
        {
            var userId = 1;
            var shop = new Shop
            {
                Name = viewModel.Name,
                Describe = viewModel.Describe,
                Mobile = viewModel.Mobile,
                WeChat = viewModel.WeChat,
                UserId = userId
            };

            await _dbContext.Shops.AddAsync(shop);
            var result = await _dbContext.SaveChangesAsync();
            return ApiResponse.Ok(result);
        }

        [HttpPut("{id}")]
        [ProducesResponseType(typeof(ResponseViewModel<int>), 200)]
        public async Task<IActionResult> Put(int id, ShopsPostViewModel viewModel)
        {
            if (id == viewModel.Id)
            {

                var shop = await _dbContext.Shops
                    .Where(s => s.Id == id)
                    .FirstAsync();
                if (shop != null)
                {
                    shop.Name = viewModel.Name;
                    shop.Describe = viewModel.Describe;
                    shop.Mobile = viewModel.Mobile;
                    shop.WeChat = viewModel.WeChat;
                    shop.UpdatedAt = DateTime.Now;
                };

                await _dbContext.Shops.UpdateAsync(shop);
                var result = await _dbContext.SaveChangesAsync();
                return ApiResponse.Ok(result);
            }

            return ApiResponse.NotFound();
        }
    }
}